import { readFileSync } from "fs";
import { resolve } from "path";
import {SmartBuffer} from "smart-buffer"

let sm = SmartBuffer.fromBuffer(readFileSync(resolve(__dirname,'../../pal3/scene/M01.cpk')))
const CPK_DEFAULT_MAX_NUM_OF_FILE = 32768
type byteType = 'Int32LE'
 class StructLayout<T extends Record<string,byteType| byteType[]>> {
   public obj = {

   } as T
   private _size = 0
   getSize(){
      return this._size
   }
   constructor(struct:T){
     for(let i in struct){
      if(Array.isArray(struct[i])){
         this._size +=  struct[i].length * 4
      } else {
         this._size +=4
      }
      this.obj[i] = struct[i]
     }
   }
   decode(sm:SmartBuffer){
      let res = {

      } as Record<keyof T,number | number[]>
     for(let i in this.obj){
      let obji = this.obj[i]
      if(Array.isArray(obji)){
         let arr = [ ] as number []
        res[i] = arr
        obji.map(item=>{
         arr.push(sm[`read${item}`]())
        })
      } else {
         res[i] = sm[`read${this.obj[i]}`]()
      }
     }
     return res
   }
 }
const obj = new StructLayout({
   Label:'Int32LE',
   Version:'Int32LE',
   TableStart:'Int32LE',
   DataStart:'Int32LE',
   MaxFileNum:'Int32LE',
   FileNum:'Int32LE',
   IsFormatted:'Int32LE',
   SizeOfHeader:'Int32LE',
   ValidTableNum:'Int32LE',
   MaxTableNum:'Int32LE',
   FragmentNum:'Int32LE',
   PackageSize:'Int32LE',
   Reserved:Array(20).fill(null).map(item=> 'Int32LE')
})

const header = obj.decode(sm)

const TableEntity = new StructLayout({
   CRC:'Int32LE',
   Flag:'Int32LE',
   FatherCRC:'Int32LE',
   StartPos:'Int32LE',
   PackedSize:'Int32LE',
   OriginSize:'Int32LE',
   ExtraInfoSize:'Int32LE',
})
const cpkTableEntitySize = TableEntity.getSize()
const indexTableSize = cpkTableEntitySize * CPK_DEFAULT_MAX_NUM_OF_FILE

var numOfFiles = header.FileNum;
var maxFileCount = header.MaxFileNum as number;
var filesFound = 0;
var indexTableOffset = 0;
let _tableEntities = {
   
}
for (let i = 0; i < maxFileCount; i++)
{
    let tableEntity = TableEntity.decode(sm)
    indexTableOffset += cpkTableEntitySize;
   //  if (tableEntity.IsEmpty() || tableEntity.IsDeleted()) continue;     
    _tableEntities[i] = tableEntity;
    filesFound++;
    if (numOfFiles == filesFound) break;
}

console.log(_tableEntities,'_tableEntities');




